/*
 * Copyright 2014 Walter Lütgenau.
 *
 * Licensed under the Apache License, Version 2.0 (the "License");
 * you may not use this file except in compliance with the License.
 * You may obtain a copy of the License at
 *
 *      http://www.apache.org/licenses/LICENSE-2.0
 *
 * Unless required by applicable law or agreed to in writing, software
 * distributed under the License is distributed on an "AS IS" BASIS,
 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
 * See the License for the specific language governing permissions and
 * limitations under the License.
 */
package offset.nodes.client.dialog.navigation.model;

import java.awt.Point;
import java.awt.Rectangle;
import netscape.javascript.JSObject;

/**
 *
 * @author Walter Lütgenau
 */
public class JSUtil {
    public static Rectangle getBoundingScreenRectangle(JSNode element) {
        int x = 0;
        int y = 0;
        
        JSNode original = element;
        while (element != null) {
            x += element.getOffsetLeft() - element.getScrollLeft() + element.getClientLeft();
            y += element.getOffsetTop() - element.getScrollTop() + element.getClientTop();
            
            element = element.getOffsetParent();
        }
        
        return new Rectangle(x, y, original.getOffsetWidth(), original.getOffsetHeight());
    }
    
    public static int getInt(JSObject object, String member) {
        Number result = (Number) object.getMember(member);
        if (result == null)
            return -1;
        return result.intValue();
    }
    
    /**
     * Return the lower left edge of the element in screen coordinates.
     * 
     * This is used to show dialogs created by clicking the element just below the element.
     * 
     * @param element the element, that has been clicked
     * @param event the onclick event
     * @return the lower left edge of the element
     */
    public static Point getLowerLeftEdge(JSNode element, JSEvent event) {
        Rectangle elementRectangle = getBoundingScreenRectangle(element);
        
        // Calculate window offset in screen coordinates
        int windowScreenX = event.getScreenX() - event.getClientX();
        int windowScreenY = event.getScreenY() - event.getClientY();
        
        // Set frame position
        return new Point(windowScreenX + (int) elementRectangle.getX(), 
                windowScreenY +  (int) (elementRectangle.getY() + elementRectangle.getHeight()));        
    }
}
